<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\UserMoneyLog as MoneyLogModel;
use app\api\library\UserMoneyLog;
use app\common\model\Withdrawal;
use think\Db;

class Balance extends Api
{
    protected $noNeedRight = '*';

    /**
     * 钱包余额
     *
     * @ApiMethod (POST)
     */
    public function amount()
    {
        $user = $this->auth->getUser();
        $data['money'] = $user->money;
        $this->success(__('Operation completed'), $data);
    }

    /**
     * 收支明细
     *
     * @ApiMethod (POST)
     * @ApiParams (name="page", type="string", required=false, description="分页页码, 默认1")
     * @ApiParams (name="limit", type="string", required=false, description="分页, 每页数据条数, 默认10")
     * @ApiParams (name="type", type="string", required=true, description="分类")
     */
    public function bill()
    {
        $user = $this->auth->getUser();
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $type = $this->request->post('type', '');
        $billModel = new MoneyLogModel();
        if ($type) {
            if ($type == 'income') {
                $billModel = $billModel->with(['serviceDetail', 'serviceDetail.service'])->whereIn('type', [1, 2]);
            } else if ($type == 'expend') {
                $billModel = $billModel->whereIn('type', [3, 4]);
            }
        }
        $billModel = $billModel->where('user_id', $user['id']);
        $fields = ['id', 'type', 'money', 'memo', 'createtime' , 'from_order_id','from_user_id'];
        $data = $billModel->field($fields)->page($page, $limit)->order('createtime', 'desc')->select();
        $user_arr = [];
        if(!empty($data)){
            $data = collection($data)->toArray();
            $user_ids = array_column($data, 'from_user_id');
            $user_arr = \app\common\model\User::whereIn('id', $user_ids)->column('nickname','id');
            $expert_arr = \app\common\model\Expert::where('id','>',0)->column('name','user_id');
        }
        foreach ($data as $key => $value) {
            $service_detail_list = $value['service_detail'] ?? [];
            $data[$key]['from_user'] = '';
            if($value['type'] == 1 || $value['type'] == 2){
                $data[$key]['from_user'] = $user_arr[$value['from_user_id']] ?? '';
                foreach ($service_detail_list as $k=>$v){
                    $service_detail_list[$k]['expert_name'] = $expert_arr[$v['expert_user_id']] ?? '';
                }
            }
            $data[$key]['service_detail'] = $service_detail_list;

        }
        $this->success(__('Operation completed'), $data);
    }

    /**
     * 申请提现
     *
     * @ApiMethod (POST)
     * @ApiParams (name="money", type="string", required=true, description="提现金额")
     * @ApiParams (name="bank_type", type="string", required=true, description="提现类型")
     */
    public function withdrawal()
    {
        $user = $this->auth->getUser();
        $money = $this->request->post('money', 0);
        $bankType = $this->request->post('bank_type', 2);
        if (empty($money) || $money <= 0) {
            $this->error(__('Invalid parameters'));
        }
        if ($money > $user['money']) {
            $this->error(__('Insufficient balance'));
        }
        $withdrawal = [
            'type' => 1,
            'user_id' => $user['id'],
            'money' => $money,
            'status' => 0,
            'bank_type' => $bankType,
        ];
        Db::startTrans();
        try {
            $result = Withdrawal::create($withdrawal);
            UserMoneyLog::expend($user['id'], UserMoneyLog::WITHDRAW, $user['id'], $result['id'], $money, $user['money'], '用户提现');
            \app\common\model\User::where('id', $user['id'])->dec('money', $money);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error(__('Withdraw apply failed'));
        }
        $this->success(__('Withdraw apply successful'));
    }

    /**
     * 提现记录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="page", type="string", required=false, description="分页页码, 默认1")
     * @ApiParams (name="limit", type="string", required=false, description="分页, 每页数据条数, 默认10")
     */
    public function withdrawalList()
    {
        $user = $this->auth->getUser();
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);
        $withdrawModel = new Withdrawal();
        $fields = ['id', 'money', 'status', 'bank_type', 'audit_time', 'audit_remark', 'createtime'];
        $data = $withdrawModel->where('user_id', $user['id'])->field($fields)->page($page, $limit)->order('createtime', 'desc')->select();
        $this->success(__('Operation completed'), $data);
    }
}